//
//  WBOAuthViewController.swift
//  SinaWebo
//
//  Created by 亚杏 on 2017/5/18.
//  Copyright © 2017年 oms. All rights reserved.
//

import UIKit
import SVProgressHUD

//通过WebView加载授权页
class WBOAuthViewController: UIViewController,UIWebViewDelegate {

    private lazy var webView = UIWebView()


    override func loadView() {

        view = webView
        view.backgroundColor = UIColor.white
        webView.scrollView.isScrollEnabled = false
        webView.delegate = self

        //设置导航栏
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBackBtn: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(AutoFillup), isBackBtn: false)
    }




    override func viewDidLoad() {
        super.viewDidLoad()

        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURL)"
        guard let url = URL(string: urlStr) else {
            return
        }
        let request = URLRequest(url: url)
        webView.loadRequest(request)

    }

    //MARK:监听返回按钮
    @objc private func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }

//    //WebView的注入，直接通过js修改本地浏览器中缓存的页面内容
    @objc private func AutoFillup(){
        print("点击自动填充")
        //准备js
        let js = "document.getElementById('userId').value = '594187213@qq.com';" + "document.getElementById('passwd').value = 'twtgogskf1990...';"
        //让webView执行js
        webView.stringByEvaluatingJavaScript(from: js)
    }

    /// MARK:UIWebViewDelegate
    ///
    /// - Parameters:
    ///   - webView: webView description
    ///   - request: 要加载的请求
    ///   - navigationType: 导航类型
    /// - Returns: 是否加载request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       // print("加载请求---\(request.url?.absoluteString ?? "")")

        //1.如果请求地址包含baidu.com，就不加载页面/否则加载
        if request.url?.absoluteString.hasPrefix(WBRedirectURL) == false {
            return true
        }
        //url之后的字符串
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            close()
            return false
        }

        //3.从query取出授权码
       let code = request.url?.query?.substring(from: "code=".endIndex)
        print("获取授权码\(String(describing: code))")
        //使用授权码获取 AccessToken
        WBNetworkManager.shared.loadaccessToken(code: code!) { (isSuccess) in
        }


        return true
    }

    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }

    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
        
    }



}
